package cn.tedu.controller;

import cn.tedu.constant.WxSelfConstant;
import cn.tedu.service.IWxService;
import cn.tedu.util.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/wx")
public class WxController {

    @Autowired
    private IWxService wxService;


    @Value("${wx.appID}")
    private String appID;
    @Value("${wx.appsecret}")
    private String appSecret;

    @GetMapping("/createMenu")
    public String createMenu(){
        wxService.createMenu();
        return "创建成功";
    }

    @GetMapping("/getCode")
    public String getCode(String code, String state,
                          HttpServletRequest request,
                          HttpServletResponse response){
        //2 第二步：通过code换取网页授权access_token
        String userinfoAccessTokenUrl = WxSelfConstant.USERINFO_ACCESS_TOKEN.replace("APPID", appID)
                .replace("SECRET", appSecret)
                .replace("CODE", code);
        String s = HttpClientUtil.doGet(userinfoAccessTokenUrl);
        System.out.println(s);
        //4 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        JSONObject jsonObject = JSON.parseObject(s);
        String userinfoUrl = WxSelfConstant.USERINFO_URL
                .replace("ACCESS_TOKEN",jsonObject.getString("access_token"))
                .replace("OPENID",jsonObject.getString("openid"));
        String userinfo = HttpClientUtil.doGet(userinfoUrl);
        // 保存用户信息
        System.out.println(userinfo);

        try {
            response.sendRedirect("https://www.baidu.com");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    @GetMapping("/getAccessToken")
    public String accessToken(){
       return  wxService.getAccessToken();
    }

    @GetMapping
    public String checkWx(String signature,String timestamp,
                          String nonce, String echostr){
       // String str = wxService.checkWx(signature,timestamp,nonce,echostr);
        return echostr ;
    }

    @PostMapping
    public String sendMessage(@RequestBody String message){
        System.out.println(message);
        return message;
    }

}
